package com.yvan.onekeylock;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {

    private ComponentName mAdminName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 无title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 状态栏透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        //获取手机设备管理器
        DevicePolicyManager dm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        //创建一个与MyDeviceAdmin相关联的组件
        mAdminName = new ComponentName(this, MyDeviceAdmin.class);
        //判断组件是否已经获取超级管理员的权
        if (dm.isAdminActive(mAdminName)) {
            dm.lockNow();
            finish();
        } else {
            showActiveAdminDialog();
        }
    }

    private void showActiveAdminDialog() {
        new AlertDialog.Builder(this)
                .setTitle("激活一键锁屏")
                .setMessage("只有允许本应用获取手机设备管理器才能使用一键锁屏功能，是否激活？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        activeDeviceAdmin();
                    }
                })
                .setCancelable(false)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.this.finish();
                    }
                })
                .show();

    }

    /**
     * 激活手机的设备管理员权限。激活后，可以执行一键锁屏。
     */
    public void activeDeviceAdmin() {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        //将组件的超级管理员权限激活
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
        startActivity(intent);
        finish();
    }

}
